﻿using Core.AdminUI.V2.Controllers.Base;
using Core.AdminUI.V2.Models;
using Core.AdminUI.V2.Models.Activity;
using Core.FrameWork.Commons.ApiResult;
using Core.FrameWork.Commons.Loging;
using Core.FrameWork.Commons.Mapping;
using Core.FrameWork.Models;
using Core.FrameWork.Models.Activity;
using Core.FrameWork.Models.Enum.Common;
using Core.FrameWork.Service.ViewBaseTree;
using Masuit.Tools.Linq;
using Masuit.Tools.Systems;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace Core.AdminUI.V2.Controllers
{
    /// <summary>
    /// 店员动态管理
    /// </summary>
    public class ActivityController : BaseController
    {
        private readonly IViewTreeConfigService _viewTreeConfigService;

        public ActivityController(AdminContext adminContext, IViewTreeConfigService viewTreeConfigService) : base(adminContext)
        {
            _viewTreeConfigService = viewTreeConfigService;
        }
        #region 视图
        public async Task<IActionResult> Index()
        {
            ViewBag.GroupList = await _viewTreeConfigService.GetSysBaseTreeByPid(BaseTreeConfig.UserClerkGroupId);

            var levelTypes = typeof(ClerkLevelType).GetFields().ToList();
            levelTypes.Remove(levelTypes.FirstOrDefault());

            ViewBag.ClerkLevelType = levelTypes.Select(s => new ClerkLevelTypeModel { Id = (int)System.Enum.Parse<ClerkLevelType>(s.Name), Name = System.Enum.Parse<ClerkLevelType>(s.Name).GetDisplay() }).ToList();
            return View();
        }
        public IActionResult Update(string Id = "")
        {
            if (!Guid.TryParse(Id, out var activityGId))
            {
                return Redirect("Index");
            }

            var activityInfo = _adminContext.Activity.Include(s => s.UserClerk).FirstOrDefault(s => s.Id.Equals(activityGId));
            if (activityInfo == null)
            {
                return Redirect("Index");
            }

            var resp = activityInfo.MapTo<Activity, RespActivity>();


            resp.Name = activityInfo.UserClerk.Name;
            resp.ClerkLevelTypeName = activityInfo.UserClerk.ClerkLevelType.GetDisplay();
            resp.UserNumber = activityInfo.UserClerk.UserNumber;
            resp.GroupId = activityInfo.UserClerk.GroupId;


            return View(resp);
        }
        #endregion

        #region 接口
        /// <summary>
        /// 获取店员动态列表数据
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <param name="userNumber"></param>
        /// <param name="name"></param>
        /// <param name="group"></param>
        /// <param name="clerkLevelType"></param>
        /// <param name="state"></param>
        /// <returns></returns>
        [HttpGet]
        [ActionDescription("获取店员动态列表数据", LogResponseData = false)]
        public async Task<PageResult<RespActivity>> GetPageList(int page = 1, int limit = 10, int userNumber = 0, string name = "", string group = "", ClerkLevelType clerkLevelType = 0, int state = 0)
        {
            Expression<Func<Activity, bool>> exp = m => true;

            if (userNumber != 0)//店员编号
            {
                exp = exp.And(s => s.UserClerk.UserNumber.Equals(userNumber));
            }
            if (!string.IsNullOrEmpty(name))//店员昵称
            {
                exp = exp.And(s => s.UserClerk.Name.Contains(name));
            }
            if (Guid.TryParse(group, out var Ggroup))//店员组
            {
                exp = exp.And(s => s.UserClerk.GroupId.Equals(Ggroup));
            }
            if (clerkLevelType != 0)//店员等级
            {
                exp = exp.And(s => s.UserClerk.ClerkLevelType.Equals(clerkLevelType));
            }
            if (state != 0)//显示组
            {
                exp = exp.And(s => s.State.Equals(state));
            }

            var list = _adminContext.Activity.Include(s => s.UserClerk).Where(exp).OrderByDescending(m => m.CreateTime)
            .Skip((page - 1) * limit)
            .Take(limit).ToList()
            .ToList();

            int count = _adminContext.Activity.Count(exp);

            var resp = list.MapTo<Activity, RespActivity>();

            foreach (var item in resp)
            {
                var activityInfo = list.FirstOrDefault(s => s.Id.Equals(item.Id));
                if (activityInfo != null)
                {
                    item.Name = activityInfo.UserClerk.Name;
                    item.ClerkLevelTypeName = activityInfo.UserClerk.ClerkLevelType.GetDisplay();
                    item.UserNumber = activityInfo.UserClerk.UserNumber;
                    item.GroupId = activityInfo.UserClerk.GroupId;
                }
            }

            return ApiRespHelp.getApiDataListByPage(resp, count, page, limit);
        }
        /// <summary>
        /// 审核店员动态
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [ActionDescription("审核店员动态", LogResponseData = true)]
        public CommonResult Approver(string Id, int State = 0)
        {
            if (!Guid.TryParse(Id, out var GId))
            {
                return ApiRespHelp.getError(-100, "动态Id 格式错误");
            }
            if (State == 0)
            {
                return ApiRespHelp.getError(-100, "审核状态错误");
            }

            var activityInfo = _adminContext.Activity.Find(GId);

            if (activityInfo == null)
            {
                return ApiRespHelp.getError(100, "未找到动态");
            }

            if (activityInfo.State == 1)
            {
                activityInfo.State = State;
                activityInfo.ApproverTime = DateTime.Now;
            }




            if (_adminContext.SaveChanges() == 0)
            {
                return ApiRespHelp.getError(-100, "操作失败");
            }

            return ApiRespHelp.getSuccess("操作成功");

        }
        /// <summary>
        /// 批量审批店员动态
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [ActionDescription("批量审批店员动态", LogResponseData = true)]
        public CommonResult BatchApprover(string Ids, int State = 0)
        {

            if (string.IsNullOrEmpty(Ids))
            {
                return ApiRespHelp.getError(-100, "Id不能为空");
            }

            if (State == 0)
            {
                return ApiRespHelp.getError(-100, "审核状态错误");
            }

            var listIds = Ids.Split(',').Select(s => Guid.Parse(s));

            var activityList = _adminContext.Activity.Where(s => listIds.Contains(s.Id)).ToList();

            if (activityList.Count == 0)
            {
                return ApiRespHelp.getError(-100, "没有找到删除的动态");
            }

            foreach (var activity in activityList)
            {
                if (activity.State == 1)
                {
                    activity.State = State;
                    activity.ApproverTime = DateTime.Now;
                }

            }


            if (_adminContext.SaveChanges() == 0)
            {
                return ApiRespHelp.getError(-100, "操作失败");
            }

            return ApiRespHelp.getSuccess("操作成功");
        }
        /// <summary>
        /// 删除店员动态
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [ActionDescription("删除动态", LogResponseData = true)]
        public CommonResult Delete(string Id)
        {
            if (!Guid.TryParse(Id, out var GId))
            {
                return ApiRespHelp.getError(-100, "动态Id 格式错误");
            }

            var activityInfo = _adminContext.Activity.Find(GId);

            if (activityInfo == null)
            {
                return ApiRespHelp.getError(100, "未找到动态");
            }

            activityInfo.IsDelete = 1;
            activityInfo.DeleteUser = Guid.Parse(CurrentUser.Id);
            activityInfo.DeleteUserName = CurrentUser.Name;
            activityInfo.DeleteTime = DateTime.Now;


            if (_adminContext.SaveChanges() == 0)
            {
                return ApiRespHelp.getError(-100, "操作失败");
            }

            return ApiRespHelp.getSuccess("操作成功");

        }
        /// <summary>
        /// 批量删除店员动态
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [ActionDescription("批量删除店员动态", LogResponseData = true)]
        public CommonResult BatchDelete(string Ids)
        {

            if (string.IsNullOrEmpty(Ids))
            {
                return ApiRespHelp.getError(-100, "Id不能为空");
            }

            var listIds = Ids.Split(',').Select(s => Guid.Parse(s));

            var activityList = _adminContext.Activity.Where(s => listIds.Contains(s.Id)).ToList();

            if (activityList.Count == 0)
            {
                return ApiRespHelp.getError(-100, "没有找到删除的动态");
            }

            foreach (var activity in activityList)
            {
                activity.IsDelete = 1;
                activity.DeleteUser = Guid.Parse(CurrentUser.Id);
                activity.DeleteUserName = CurrentUser.Name;
                activity.DeleteTime = DateTime.Now;
            }


            if (_adminContext.SaveChanges() == 0)
            {
                return ApiRespHelp.getError(-100, "操作失败");
            }

            return ApiRespHelp.getSuccess("操作成功");
        }
        #endregion
    }
}
